# image.py
from fastapi import APIRouter, HTTPException
from fastapi.responses import FileResponse, JSONResponse
from pathlib import Path

router = APIRouter()

# 图片文件夹路径
IMAGE_DIR = Path(__file__).parent.parent / "assets" / "image"

@router.get("/file/{filename}")
async def get_image_file(filename: str):
    # 防止路径穿越攻击
    safe_filename = Path(filename).name
    file_path = IMAGE_DIR / safe_filename

    if not file_path.exists():
        raise HTTPException(status_code=404, detail="图片文件未找到")

    return FileResponse(file_path)


@router.get("/list", response_class=JSONResponse)
async def list_image_files():
    image_extensions = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"}
    image_files = [f.name for f in IMAGE_DIR.iterdir() if f.suffix.lower() in image_extensions]

    if not image_files:
        raise HTTPException(status_code=404, detail="没有找到任何图片文件")
    
    return {
        "count": len(image_files),
        "data": image_files
    }
